SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
IF EXISTS (SELECT * FROM tempdb..sysobjects WHERE id=OBJECT_ID('tempdb..#tmpErrors')) DROP TABLE #tmpErrors
GO
CREATE TABLE #tmpErrors (Error int)
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
BEGIN TRANSACTION
GO

/*===================================BEGIN=================================*/

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROC spRollBackTeamContactAssignation
	@TRANSACTION_ID UNIQUEIDENTIFIER
AS
BEGIN
	BEGIN TRANSACTION
	
	--DELETE CURRENT ASSIGNATION
	DELETE FROM dbo.TEAMS_CONTACT_ASSIGNATION WHERE TRANSACTION_ID = @TRANSACTION_ID
	AND REPLACE_TRANSACTION_ID IS NULL
	
	--REMOVE REPLACE_TRANSACTION_ID FROM LAST ASSIGNATION
	UPDATE dbo.TEAMS_CONTACT_ASSIGNATION
	SET REPLACE_TRANSACTION_ID = NULL
	WHERE REPLACE_TRANSACTION_ID = @TRANSACTION_ID
	
	COMMIT TRANSACTION
END

/*===================================END=================================*/


IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO

IF EXISTS (SELECT * FROM #tmpErrors) ROLLBACK TRANSACTION
GO
IF @@TRANCOUNT>0 BEGIN
PRINT 'The database update succeeded'

-- Record the script update
INSERT INTO dbo.[SchemaChanges]
       ([MajorReleaseNumber]
       ,[MinorReleaseNumber]
       ,[BuildReleaseNumber]
       ,[RevisionReleaseNumber]
       ,[ScriptName]
       ,[DateApplied]
       ,[Description])
VALUES
       ('1'
       ,'00'
       ,'01'
       ,'010'
       ,'Upgrade-1.00.01.010.sql'	   
       ,GETDATE()
	   ,'Create proc roll back team contact assignation')
	   COMMIT TRANSACTION
END
ELSE PRINT 'The database update failed'
GO
DROP TABLE #tmpErrors
GO        

